from django.contrib.auth.decorators import login_required
from django.core.serializers import json
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.utils.six import wraps

from goods.models import User, Goods, Category
from goods.taobao.Crawler import Crawler

global paChouStatus
paChouStatus = False


# 说明：这个装饰器的作用，就是在每个视图函数被调用时，都验证下有没法有登录，
# 如果有过登录，则可以执行新的视图函数，
# 否则没有登录则自动跳转到登录页面。
def check_login(f):
    @wraps(f)
    def inner(request, *arg, **kwargs):
        if request.session.get('is_login') == '1':
            return f(request, *arg, **kwargs)
        else:
            return redirect('/login')

    return inner


@check_login
def main(request):
    userName = request.session.get("user_name")
    keyword = request.GET.get("keyword")  # 搜索关键词
    category = request.GET.get("category")  # 分类

    print(keyword)
    print(category)
    data = []
    state = 0
    if keyword is not None and keyword != "":
        data = list(Goods.objects.filter(title__contains=keyword).order_by('-sales_counter'))
        print(data)
        state = 1
    if category is not None and category != "":
        data = list(Goods.objects.filter(category=category).order_by('-sales_counter'))
        state = 1
    if keyword is None and category is None:
        data = list(Goods.objects.all().order_by('-sales_counter'))
        state = 0
    categoryList = list(Category.objects.all())
    for item in categoryList:
        item.id = item.id % 3
    print(state)
    if keyword is None:
        keyword = ""
    return render(request, 'main.html',
                  {'keyword': keyword, 'userName': userName, 'data': data, 'category': categoryList, 'state': state,'size':len(data)})


def pachou(request):
    # 启动爬虫服务
    global paChouStatus
    paChouStatus = True
    print("启动爬虫服务")
    print( request.POST.get('taobao_name'))
    print( request.POST.get('taobao_pwd'))
    return render(request, 'pachou.html', {'taobao_name': request.POST.get('taobao_name'), 'taobao_pwd': request.POST.get('taobao_pwd')})


def startPachou(request):
    postBody = request.body
    print(postBody)
    import json
    json_result = json.loads(postBody)
    print(json_result)
    #global paChouStatus
    paChouStatus = Crawler().start(json_result['taobao_name'], json_result['taobao_pwd'])
    return HttpResponse(paChouStatus)


def getStatus(request):
    return HttpResponse(paChouStatus)


def outLogin(request):
    request.session.clear()
    return redirect('/login')


def login(request):
    if request.method == "POST":
        user_name = request.POST.get("user_name")
        user_pwd = request.POST.get("user_pwd")
        user = User.objects.filter(user_name=user_name, user_pwd=user_pwd).values('id', 'user_name')
        if user.count() == 0:
            return render(request, 'login.html', {'message': "账号密码不存在"})
        request.session['is_login'] = '1'  # 这个session是用于后面访问每个页面（即调用每个视图函数时要用到，即判断是否已经登录，用此判断）
        data = list(user)
        request.session['user_name'] = data[0]['user_name']
        return redirect('/')
    return render(request, 'login.html')


def register(request):
    print(request.body)
    user_name = request.POST.get("user_name")
    user_pwd = request.POST.get("user_pwd")
    user = User.objects.filter(user_name=user_name).values('id', 'user_name')
    print(user)
    if user.count() > 0:
        return render(request, 'login.html', {'message': "账号已经注册，请登录"})
    print(user_name)
    user = User(user_name=user_name, user_pwd=user_pwd)
    user.save()
    return render(request, 'login.html', {'message': "注册成功！"})
